package com.samen.sample;

import java.io.File;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.samen.imgtools.R;
import com.samen.util.DownloadTask;
import com.samen.util.DownloadTask.DownloadProgressListener;
/**
 * sample implementaion of DownloadTask
 * @author Santosh Kumar D
 *
 */
public class DownloadActivity extends Activity implements DownloadProgressListener {

	TextView textView;
	DownloadTask downloadTask;
	File file;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textView = (TextView) findViewById(R.id.txt);
		String str = getExternalFilesDir(null) + "/video1.m4v";
		file = new File(str);
		if (file.exists()) {
			playVideo();
		} else {
			downloadTask = new DownloadTask(this, file);
			downloadTask.execute("http://www.myheartmirror.com/myheartmirror/services/iShare%20English.m4v");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (downloadTask != null)
				downloadTask.cancel(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void downloadProgress(int progress) {
		textView.setText("" + progress);
	}

	@Override
	public void downloadComplete(boolean b) {
		if (b)
			playVideo();
		else
			Toast.makeText(this, "download error", 0).show();
	}

	private void playVideo() {
		VideoView videoHolder = new VideoView(this);
		setContentView(videoHolder);
		videoHolder.setMediaController(new MediaController(this));
		videoHolder.setVideoURI(Uri.parse("file://" + file.getAbsolutePath()));
		videoHolder.requestFocus();
		videoHolder.start();
	}

}